<!-- 年规 -->
<template>
  <view>
    <u-navbar :is-back="false" :background="{ background: 'linear-gradient(to bottom, #5c616a 0%, #4c4f55 100%)' }"
      :border-bottom="false">
    
      <view v-if="currentClub" class="mx-4 flex items-center" @click="state.showSocietySelectPop = true">
        <view class="pr-2 text-32 text-white leading-4 text-maxline-1">{{ currentClub?.club?.club_name }}</view>
        <image class="w-32 h-32" src="/static/images/common/ic_exchange.png" />
      </view>
      <image v-else class="mx-4 w-214 h-48" src="/static/images/common/img_top_logo.jpg" />
    </u-navbar>
    <view class="relative px-4 pb-4">
      <image class="absolute top-0 left-0 w-full h-282" src="/static/images/common/img_bg_plan.jpg" mode="aspectFill" />
      <view class="relative flex justify-center items-center h-56 pt-2">
        <view class="flex-1 h-40 flex justify-end items-center px-4" @click="onYearChange('pre')">
          <image class="w-16 h-28" src="/static/images/common/ic_arrow_plan_left.jpg" />
        </view>
        <view class="c-#fff text-40">{{ year }}年度规划</view>
        <view class="flex-1 h-40 flex items-center px-4" @click="onYearChange('next')">
          <image class="w-16 h-28" src="/static/images/common/ic_arrow_plan_right.jpg" />
        </view>
      </view>
      <view v-if="!state.target" class="relative h-297 flex flex-col items-center justify-center mt-4"
        @click="onTargetAddClick">
        <image class="absolute w-686 h-297" src="/static/images/common/img_bg_plan_card.jpg" />
        <image class="relative w-120 h-120" src="/static/images/common/img_plan_add.jpg" />
        <view class="relative mt-4 c-#fff text-28">添加年度目标</view>
      </view>
      <view v-else class="relative h-325 flex flex-col items-center justify-center mt-4">
        <image class="absolute w-686 h-325" src="/static/images/common/img_bg_plan_card.jpg" />
        <view class="relative w-full px-4">
          <view class="flex">
            <text class="flex-1 c-#fff text-60 text-center font-bold">{{ numFormat(state.target?.annual_target || 0)
            }}W</text>
            <view v-if="isSocietyManager" class="absolute right-30 top-10 label-performance"
              @click="navigate(`/package_plan/pages/performance/user/index`)">员工业绩</view>
          </view>
          <view v-if="state.target?.percent < 100" class="flex items-center justify-center mb-2"
            :class="[{ 'pointer-events-none': !isSocietyManager }]"
            @click="navigate(`/package_plan/pages/performance/add`)">
            <view class="c-#fff text-28"> 年度目标({{ currency?.unit }})</view>
            <image v-if="isSocietyManager" class="ml-2 w-16 h-28" src="/static/images/common/ic_arrow_plan_right.jpg" />
          </view>

          <view v-else class="flex items-center justify-center mb-2"
            :class="[{ 'pointer-events-none': !isSocietyManager }]">
            <view class="c-#fff text-28"> 年度目标已完成!</view>
          </view>

          <view v-if="state.target?.percent > 100" class="flex justify-end absolute right-15 top-95">
            <view class="marker-label px-2 flex items-center">
              <image class="w-26 h-24 mr-1" src="/static/images/common/ic_like_finger.jpg" />
              <view>超{{ Number(state.target?.percent - 100).toFixed(2) }}%</view>
            </view>
          </view>

          <u-line-progress :active-color="activeColor" height="12" :inactive-color="inactiveColor" :percent="percent"
            :show-percent="false"></u-line-progress>


          <view class="flex justify-center mt-1 c-#fff text-24">{{ state.target?.percent || 0 }}%</view>
          <view class="flex items-center py-2 c-#fff text-24">
            <view class="flex-1">现已完成金额：{{ numFormat(state.target?.finish_money || 0) }}W({{ currency?.unit }})</view>
            <view class="flex-shrink-0">{{ nowDate }}</view>
          </view>
        </view>
      </view>
      <view class="grid grid-cols-3 w-full mt-1">
        <view class="item-style mt-2" v-for="(  item, index  ) in   menuList  " :key="index" @click="onMenuClick(item)">
          <image :src="item.url" :style="{ width: `${item.width}rpx`, height: `${item.height}rpx` }" />
          <view class="mt-2 c-#333 text-28">{{ item.name }}</view>
        </view>
      </view>
      <view class="flex items-center my-3 c-#333">
        <view class="flex-1 text-40 font-600">每月必做事件</view>
        <view v-if="state.monthEvents.length > 0" class="flex-shrink-0 flex" @click="onMonthEventExport">
          <image class="w-25 h-28" src="/static/images/common/ic_export.png" />
          <view class="ml-2 text-28 leading-3.5">导出</view>
        </view>
      </view>
      <view v-if="state.monthEvents.length == 0" class="flex flex-col items-center justify-center py-15"
        :class="[{ 'pointer-events-none': userStore.isLogin }]" @click="navigate('/package_user/pages/common/login')">
        <image class="w-396 h-332" src="/static/images/empty/img_empty_work.jpg" />
        <view class="mt-4 text-28 c-#666">{{ userStore.isLogin ? '暂无事件' : '请先登录' }}</view>
      </view>
      <view v-else>
        <view v-for="(  item, index  ) in   state.monthEvents  " :key="index" class="mb-4">
          <view class="c-#333 text-28 mb-1 mt-3">{{ item.month }}月</view>
          <view class="item-month">
            <view v-for="(  event, eventIndex  ) in   item.event  " :key="eventIndex" class="flex-1 py-1">
              <view class="flex items-center">
                <view v-if="event.status == 0" class="event-indicator" />
                <u-icon v-else-if="event.status == 1" class="flex-shrink-0" name="checkmark-circle-fill" color="#F4AF22"
                  size="30" />
                <u-icon v-else name="close-circle-fill" class="flex-shrink-0" color="#999" size="30" />
                <view class="flex-1 c-#333 text-28 ml-2"><text class="font-bold mr-1">{{ item.month }}/{{ event.day
                }}</text>{{ event.content || '' }}</view>
                <view v-if="event.status == 0 && isShowVerify(event)" class="flex-shrink-0 flex items-center"
                  @click="onMonthEventVerifyClick(event)">
                  <view class="mr-1 c-#ff513a text-28">待核实</view>
                  <u-icon name="arrow-right" size="23" color="#ff523a" />
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <!-- 每月事件核实弹窗 -->
    <u-modal v-model="state.showVerifyModal" title="事件核实" border-radius="12" show-cancel-button mask-close-able
      confirm-color="#F4AF22" @confirm="onMonthEventVerifyConfirm">
      <view class="py-6 flex justify-center items-center">
        <u-radio-group v-model="state.monthEventVerifyStatus" shape="circle">
          <u-radio :name="1" size="32" active-color="#F4AF22">已完成</u-radio>
          <u-radio :name="2" size="32" active-color="#F4AF22">未完成</u-radio>
        </u-radio-group>
      </view>
    </u-modal>
    <!-- 学社切换弹窗 -->
    <plan-pop v-if="isLogin" :show="state.showSocietySelectPop" :club_id="currentClub?.club_id" @switch="onSwitchSociety"
      @enter="onEnterSociety" @close="state.showSocietySelectPop = false" />
      <button size="default" type="" open-type="contact">
      <view class="w-136 h-136 z-1000 fixed bottom-100 right-30">
        <image class="w-136 h-136" src="/static/images/common/ic_service.jpg"></image>
      </view>
    </button>
  </view>
</template>
<script setup>
import { navigate, showModal, showToast } from '@/common/util/uni';
import { downloadFile } from '@/common/util/util';
import { menuList, currencyList } from '@/common/constant/plan'
import { numFormat } from '@/common/util/format';
import { useUserStore } from '@/store/user';
import { usePlanStore } from '@/store/plan';
import { getTargetDetail, getMonthEvents, postTargetVerify, getMonthEventExportUrl } from '@/common/http/module/plan'
import dayjs from 'dayjs';

const userStore = useUserStore()
const planStore = usePlanStore()

const activeColor = computed(() => {
  if (state.target.percent > 100) {
    return '#F8DC61'
  } else {
    return '#fff'
  }
})

const inactiveColor = computed(() => {
  if (state.target.percent > 100) {
    return '#F8DC61'
  } else {
    return '#e9d5b1'
  }
})

const percent = computed(() => {
  if (state.target.percent > 100) {
    return '85'
  } else {
    return state.target.percent
  }
})

const state = reactive({
  target: '',
  monthEvents: [],
  monthEvent: '',
  monthEventVerifyStatus: '',
  showVerifyModal: false,
  showSocietySelectPop: false
});

const year = computed(() => planStore.year)
const currency = computed(() => currencyList.find(item => item.value == state.target?.currency))
const currentClub = computed(() => userStore.currentSociety)
const isLogin = computed(() => userStore.isLogin)
const isSocietyManager = computed(() => userStore.isSocietyManager || userStore.isSocietyCreator)
const isShowVerify = computed(() => (item) => isSocietyManager.value || userStore.userInfo?.id == item.charge_id)
const nowDate = dayjs().format('MM/DD')

watch(() => currentClub.value, (val) => {
  if (!val) return
  loadData()
})

function onYearChange(type) {
  const result = year.value + (type == 'pre' ? -1 : 1)
  planStore.changeYear(result)
  loadData()
}

function loadData() {
  if (!userStore.isLogin) return
  if (!currentClub.value) return

  planStore.loadTarget()

  getTargetDetail(userStore.currentSocietyId, year.value).then(res => {
    state.target = res.data
    if (!res.data && !isSocietyManager.value) {
      showEmptyTip()
    }
  })

  getMonthEvents(userStore.currentSocietyId, year.value).then(res => {
    state.monthEvents = res.data?.filter(item => item.event && item.event?.length > 0)
  })
}

function onTargetAddClick() {
  if (!userStore.isLogin) {
    navigate('/package_user/pages/common/login')
    return false
  }
  if (!isSocietyManager.value) {
    showModal({
      content: '无内容'
    })
    return
  }
  if (!currentClub.value) {
    showClubTip()
    return false
  }
  navigate(`/package_plan/pages/performance/add`)
}

function onMonthEventExport() {
  getMonthEventExportUrl(userStore.currentSocietyId, year.value).then(res => {
    const url = res.data
    console.log('onMonthEventExport', url);
    downloadFile(url, '正在导出').then(res => {
      console.log('downloadFile', res);
      const fileType = url.substring(url.lastIndexOf('.') + 1)
      uni.openDocument({
        filePath: res,
        fileType
      })
    })
  })
}

function onMonthEventVerifyClick(event) {
  state.monthEvent = event
  state.showVerifyModal = true
}

function onMonthEventVerifyConfirm() {
  const params = {
    event_id: state.monthEvent.id,
    type: state.monthEvent.type,
    status: state.monthEventVerifyStatus,
  }
  postTargetVerify(params).then(() => {
    showToast('提交成功')
    loadData()
  })
}

function onSwitchSociety(e) {
  userStore.changeSociety(e)
  state.showSocietySelectPop = false
}

function onEnterSociety(e) {
  userStore.changeSociety(e)
  state.showSocietySelectPop = false
  navigate(`/package_society/pages/society/index?tabId=0&club_id=${e.club_id}`)
}

function onMenuClick(item) {
  if (!checkIfCanAddTarget()) {
    return
  }
  navigate(item.route)
}

function checkIfCanAddTarget() {
  if (!userStore.isLogin) {
    navigate('/package_user/pages/common/login')
    return false
  }
  if (!userStore.isVip && !userStore.isConsultant && !currentClub.value) {
    showVipTip()
    return false
  }
  if (!currentClub.value) {
    showClubTip()
    return false
  }
  return true
}

function showVipTip() {
  showModal({
    title: '温馨提示',
    content: '很抱歉，由于您目前还没有创建或加入任一学社，所以暂时不能编辑或查看年度规划内容哦',
    confirmText: '知道了',
    showCancel: false,
  })
}

function showClubTip() {
  showModal({
    title: '温馨提示',
    content: '很抱歉，由于您目前还没有创建或加入任一学社，所以暂时不能编辑或查看年度规划内容哦',
    confirmText: '去创建',
    showCancel: false,
    success: ({ confirm }) => {
      if (!confirm) return
      navigate('/package_society/pages/society/add')
    }
  })
}

function showEmptyTip() {
  showModal({
    title: '温馨提示',
    content: '该学社管理人员有点懒哦~ 暂时还没有添加规划内容,您可以去提醒一下哦',
    confirmText: '知道了',
    showCancel: false
  })
}

onShow(() => {
  loadData()
})
</script>

<style lang="scss" scoped>
.item-style {
  width: 218rpx;
  height: 132rpx;
  border-radius: 12rpx;
  background-color: #FFFFFF;
  box-shadow: -1.2246468525851679e-16px 2px 6px 0px rgba(206, 143, 12, 0.1);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.button-add {
  width: 526rpx;
  height: 68rpx;
  border-radius: 10rpx;
  background-color: #F4AF22;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
}

.label-performance {
  padding: 4rpx 12rpx;
  border-radius: 4rpx;
  border: 4rpx solid #FFFFFF;
  color: #fff;
  font-size: 24rpx;

}

.item-month {
  width: 100%;
  border-radius: 12rpx;
  background-color: #FFFFFF;
  box-shadow: -1.2246468525851679e-16px 2px 6px 0px rgba(206, 143, 12, 0.1);
  border-left: 8rpx solid #F4AF22;
  padding: 24rpx 32rpx;
}

.event-indicator {
  width: 26rpx;
  height: 26rpx;
  margin: 0 2rpx;
  border-radius: 50%;
  border: 2rpx solid #F4AF22;
}

.marker-label {
  position: relative;
  font-size: 24rpx;
  border-radius: 8rpx;
  font-weight: 500;
  background: #F8DC61;
  border: 1px solid #F8DC61;
  color: #FF513A;
  text-align: center;
  line-height: 20px;

  &::before {
    position: absolute;
    left: 50%;
    top: 20px;
    transform: translate(-50%, 0);
    z-index: 3;
    border-top: 6px solid #F8DC61;
    border-right: 6px solid transparent;
    border-left: 6px solid transparent;
    /* box-sizing: content-box; */
    width: 0;
    height: 0;
  }

  &::after {
    content: "";
    position: absolute;
    left: 50%;
    top: 21px;
    transform: translate(-50%, 0);
    z-index: 2;
    border-top: 6px solid #F8DC61;
    border-right: 6px solid transparent;
    border-left: 6px solid transparent;
    width: 0;
    height: 0;
  }
}
</style>
